<template>
  <div class="register-container">
    <div class="register-card">
      <h2 class="register-title">注册新账号</h2>
      
      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-group">
          <label for="name">姓名</label>
          <input
            id="name"
            v-model="formData.name"
            type="text"
            class="form-control"
            placeholder="请输入您的姓名"
            required
            @blur="validateName"
          />
          <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
        </div>

        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            id="email"
            v-model="formData.email"
            type="email"
            class="form-control"
            placeholder="请输入您的邮箱"
            required
            @blur="validateEmail"
          />
          <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="formData.password"
            type="password"
            class="form-control"
            placeholder="请输入密码（至少6位）"
            required
            @blur="validatePassword"
          />
          <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
            id="confirmPassword"
            v-model="formData.confirmPassword"
            type="password"
            class="form-control"
            placeholder="请再次输入密码"
            required
            @blur="validateConfirmPassword"
          />
          <span v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</span>
        </div>

        <div class="form-group">
          <label for="role">角色</label>
          <select
            id="role"
            v-model="formData.role"
            class="form-control"
            required
          >
            <option value="teacher">教师</option>
            <option value="student">学生</option>
          </select>
        </div>

        <button 
          type="submit" 
          class="submit-button"
          :disabled="loading || !isFormValid"
        >
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>

      <div class="login-link">
        已有账号？<router-link to="/login">立即登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useMessage } from '@/composables/useMessage'

const router = useRouter()
const authStore = useAuthStore()
const { showMessage } = useMessage()

// 表单数据
const formData = ref({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
  role: 'teacher'
})

// 错误信息
const errors = ref({
  name: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 加载状态
const loading = ref(false)

// 验证姓名
const validateName = () => {
  if (!formData.value.name.trim()) {
    errors.value.name = '姓名不能为空'
    return false
  }
  if (formData.value.name.trim().length < 2) {
    errors.value.name = '姓名至少需要2个字符'
    return false
  }
  errors.value.name = ''
  return true
}

// 验证邮箱
const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!formData.value.email) {
    errors.value.email = '邮箱不能为空'
    return false
  }
  if (!emailRegex.test(formData.value.email)) {
    errors.value.email = '请输入有效的邮箱地址'
    return false
  }
  errors.value.email = ''
  return true
}

// 验证密码
const validatePassword = () => {
  if (!formData.value.password) {
    errors.value.password = '密码不能为空'
    return false
  }
  if (formData.value.password.length < 6) {
    errors.value.password = '密码至少需要6个字符'
    return false
  }
  // 密码强度检查
  const hasLetter = /[a-zA-Z]/.test(formData.value.password)
  const hasNumber = /[0-9]/.test(formData.value.password)
  if (!hasLetter || !hasNumber) {
    errors.value.password = '密码必须包含字母和数字'
    return false
  }
  errors.value.password = ''
  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!formData.value.confirmPassword) {
    errors.value.confirmPassword = '请确认密码'
    return false
  }
  if (formData.value.password !== formData.value.confirmPassword) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    return false
  }
  errors.value.confirmPassword = ''
  return true
}

// 表单是否有效
const isFormValid = computed(() => {
  return formData.value.name.trim() &&
    formData.value.email &&
    formData.value.password &&
    formData.value.confirmPassword &&
    formData.value.password === formData.value.confirmPassword &&
    !errors.value.name &&
    !errors.value.email &&
    !errors.value.password &&
    !errors.value.confirmPassword
})

// 处理注册
const handleRegister = async () => {
  // 验证所有字段
  const isNameValid = validateName()
  const isEmailValid = validateEmail()
  const isPasswordValid = validatePassword()
  const isConfirmPasswordValid = validateConfirmPassword()

  if (!isNameValid || !isEmailValid || !isPasswordValid || !isConfirmPasswordValid) {
    return
  }

  loading.value = true
  try {
    await authStore.register({
      name: formData.value.name.trim(),
      email: formData.value.email.trim(),
      password: formData.value.password,
      role: formData.value.role as 'teacher' | 'student'
    })
    
    showMessage('注册成功！即将跳转到登录页面...', 'success')
    
    // 延迟跳转到登录页
    setTimeout(() => {
      router.push('/login')
    }, 2000)
  } catch (error: any) {
    showMessage(error.message || '注册失败，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  padding: 20px;
}

.register-card {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 450px;
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.register-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #666;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #409eff;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.submit-button {
  background-color: #409eff;
  color: white;
  padding: 12px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 10px;
}

.submit-button:hover:not(:disabled) {
  background-color: #66b1ff;
}

.submit-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>